package com.h2cloud.JUCTest.threadPool;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

import static com.h2cloud.JUCTest.TimeUtil.Sleeper.sleep;

/**
 * @Package: com.h2cloud.JUCTest.threadPool
 * @ClassName: SynchronousQueue_test
 * @Author: h2cloud
 * @CreateTime: 2022/5/31 12:41 上午
 * @Description:
 */

/**
 * SynchronousQueue 0容量大小的队列测试
 */
@Slf4j
public class SynchronousQueue_test {


	public static void main(String[] args) {
		SynchronousQueue<Integer> integers = new SynchronousQueue<>();
		new Thread(() -> {
			try {
				log.debug("putting {} ", 1);
				// 对比一下两种方法的区别
				// integers.put(1);
				boolean offer = integers.offer(1);
				System.out.println(offer);

				log.debug("{} putted...", 1);
				log.debug("putting...{} ", 2);
				integers.put(2);
				log.debug("{} putted...", 2);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}, "t1").start();

		sleep(2);
		new Thread(() -> {
			try {
				log.debug("taking {}", 1);
				integers.take();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}, "t2").start();

		sleep(1);
		new Thread(() -> {
			try {
				log.debug("taking {}", 2);
				integers.take();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}, "t3").start();

		ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
		List<Future<?>> list = new ArrayList<>();
		long l = System.currentTimeMillis();
		for (int i = 0; i < 10; i++) {
			final int index = i;
			Runnable r = () -> {
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			};
			Future<?> submit = cachedThreadPool.submit(r);
			list.add(submit);
		}
		list.forEach(f -> {
			try {
				f.get();
			} catch (InterruptedException e) {
				e.printStackTrace();
			} catch (ExecutionException e) {
				e.printStackTrace();
			}
		});
		System.out.println(System.currentTimeMillis() - l);
	}
}
